<template>
  <div class="login-form-container">
    <h3 class="login-form-title">{{ t("login.login") }}</h3>
    <el-form
      ref="loginFormRef"
      :model="loginFormData"
      :rules="loginRules"
      size="large"
      :validate-on-rule-change="false"
      class="login-form"
    >
      <!-- 用户名 -->
      <el-form-item prop="username" class="form-item">
        <el-input
          v-model.trim="loginFormData.username"
          :placeholder="t('login.username')"
          class="login-input"
        >
          <template #prefix>
            <el-icon class="login-icon"><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-tooltip :visible="isCapsLock" :content="t('login.capsLock')" placement="right">
        <el-form-item prop="password" class="form-item">
          <el-input
            v-model.trim="loginFormData.password"
            :placeholder="t('login.password')"
            type="password"
            show-password
            class="login-input"
            @keyup="checkCapsLock"
            @keyup.enter="handleLoginSubmit"
          >
            <template #prefix>
              <el-icon class="login-icon"><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>

      <!-- 验证码 -->
      <!-- <el-form-item prop="captchaCode">
        <div flex>
          <el-input
            v-model.trim="loginFormData.captchaCode"
            :placeholder="t('login.captchaCode')"
            @keyup.enter="handleLoginSubmit"
          >
            <template #prefix>
              <div class="i-svg:captcha" />
            </template>
          </el-input>
          <div cursor-pointer h="[40px]" w="[120px]" flex-center ml-10px @click="getCaptcha">
            <el-icon v-if="codeLoading" class="is-loading"><Loading /></el-icon>

            <img
              v-else
              object-cover
              border-rd-4px
              p-1px
              shadow="[0_0_0_1px_var(--el-border-color)_inset]"
              :src="captchaBase64"
              alt="code"
            />
          </div>
        </div>
      </el-form-item> -->

      <div class="form-options">
        <el-checkbox v-model="loginFormData.rememberMe" class="remember-checkbox">
          {{ t("login.rememberMe") }}
        </el-checkbox>
        <!-- <el-link
          type="primary"
          underline="never"
          class="forgot-link"
          @click="toOtherForm('resetPwd')"
        >
          {{ t("login.forgetPassword") }}
        </el-link> -->
      </div>

      <!-- 登录按钮 -->
      <el-form-item class="form-item">
        <el-button
          :loading="loading"
          type="primary"
          class="login-button"
          @click="handleLoginSubmit"
        >
          {{ t("login.login") }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- <div class="register-section">
      <el-text size="default" class="register-text">{{ t("login.noAccount") }}</el-text>
      <el-link
        type="primary"
        underline="never"
        class="register-link"
        @click="toOtherForm('register')"
      >
        {{ t("login.reg") }}
      </el-link>
    </div> -->

    <!-- 第三方登录 -->
    <!-- <el-divider>
      <el-text size="small">{{ t("login.otherLoginMethods") }}</el-text>
    </el-divider>
    <div class="flex-center gap-x-5 w-full text-[var(--el-text-color-secondary)]">
      <CommonWrapper>
        <div text-20px class="i-svg:wechat" />
      </CommonWrapper>
      <CommonWrapper>
        <div text-20px cursor-pointer class="i-svg:qq" />
      </CommonWrapper>
      <CommonWrapper>
        <div text-20px cursor-pointer class="i-svg:github" />
      </CommonWrapper>
      <CommonWrapper>
        <div text-20px cursor-pointer class="i-svg:gitee" />
      </CommonWrapper>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import { LocationQuery, RouteLocationRaw, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
// import AuthAPI, { type LoginFormData } from "@/api/auth.api";
import { type LoginFormData } from "@/api/auth.api";
import router from "@/router";
import { useUserStore } from "@/store";
// import CommonWrapper from "@/components/CommonWrapper/index.vue";
import { Auth } from "@/utils/auth";

const { t } = useI18n();
const userStore = useUserStore();
const route = useRoute();

// onMounted(() => getCaptcha());

const loginFormRef = ref<FormInstance>();
const loading = ref(false); // 按钮 loading 状态
const isCapsLock = ref(false); // 是否大写锁定
// const captchaBase64 = ref(); // 验证码图片Base64字符串
const rememberMe = Auth.getRememberMe();

const loginFormData = ref<LoginFormData>({
  username: "厂家",
  password: "01230123",
  captchaKey: "",
  captchaCode: "",
  rememberMe: rememberMe,
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    // captchaCode: [
    //   {
    //     required: true,
    //     trigger: "blur",
    //     message: t("login.message.captchaCode.required"),
    //   },
    // ],
  };
});

// 获取验证码
// const codeLoading = ref(false);
// function getCaptcha() {
//   codeLoading.value = true;
//   AuthAPI.getCaptcha()
//     .then((data) => {
//       loginFormData.value.captchaKey = data.captchaKey;
//       captchaBase64.value = data.captchaBase64;
//     })
//     .finally(() => (codeLoading.value = false));
// }

// 登录提交处理
async function handleLoginSubmit() {
  try {
    // 1. 表单验证
    const valid = await loginFormRef.value?.validate();
    if (!valid) return;

    loading.value = true;

    // 2. 执行登录
    await userStore.login(loginFormData.value);

    // 3. 获取用户信息
    await userStore.getUserInfo();

    // 4. 解析并跳转目标地址
    const redirect = resolveRedirectTarget(route.query);
    await router.push(redirect);

    // 5. 记住我功能已实现，根据用户选择决定token的存储方式:
    // - 选中"记住我": token存储在localStorage中，浏览器关闭后仍然有效
    // - 未选中"记住我": token存储在sessionStorage中，浏览器关闭后失效
  } catch (error) {
    // 6. 统一错误处理
    // getCaptcha(); // 刷新验证码
    console.error("登录失败:", error);
  } finally {
    loading.value = false;
  }
}

/**
 * 解析重定向目标
 * @param query 路由查询参数
 * @returns 标准化后的路由地址对象
 */
function resolveRedirectTarget(query: LocationQuery): RouteLocationRaw {
  // 默认跳转路径
  const defaultPath = "/";

  // 获取原始重定向路径
  const rawRedirect = (query.redirect as string) || defaultPath;

  try {
    // 6. 使用Vue Router解析路径
    const resolved = router.resolve(rawRedirect);
    return {
      path: resolved.path,
      query: resolved.query,
    };
  } catch {
    // 7. 异常处理：返回安全路径
    return { path: defaultPath };
  }
}

// 检查输入大小写
function checkCapsLock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState("CapsLock");
  }
}

const emit = defineEmits(["update:modelValue"]);
function toOtherForm(type: "register" | "resetPwd") {
  emit("update:modelValue", type);
}
</script>

<style lang="scss" scoped>
.login-form-container {
  width: 100%;
}

.login-form-title {
  text-align: center;
  margin: 0 0 24px 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--login-text-primary);
}

.login-form {
  .form-item {
    margin-bottom: 20px;
  }

  .login-input {
    :deep(.el-input__wrapper) {
      background: var(--login-input-bg);
      border: 1px solid var(--login-input-border);
      border-radius: 8px;
      transition: all 0.3s ease;
      box-shadow: none;

      &:hover {
        border-color: var(--login-primary-light);
      }

      &.is-focus {
        border-color: var(--login-input-focus-border);
        box-shadow: 0 0 0 2px rgba(0, 124, 198, 0.1);
      }
    }

    :deep(.el-input__inner) {
      color: var(--login-text-primary);
      font-size: 14px;
      height: 44px;

      &::placeholder {
        color: var(--login-text-secondary);
      }
    }

    :deep(.el-input__prefix) {
      color: var(--login-primary-color);
    }
  }

  .login-button {
    width: 100%;
    height: 44px;
    background: var(--login-primary-gradient);
    border: none;
    border-radius: 8px;
    font-weight: 600;
    font-size: 16px;
    transition: all 0.3s ease;

    &:hover {
      background: var(--login-button-hover);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 124, 198, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .remember-checkbox {
      :deep(.el-checkbox__input) {
        .el-checkbox__inner {
          border-color: var(--login-input-border);

          &:hover {
            border-color: var(--login-primary-light);
          }
        }

        &.is-checked {
          .el-checkbox__inner {
            background-color: var(--login-primary-color);
            border-color: var(--login-primary-color);
          }
        }
      }

      :deep(.el-checkbox__label) {
        color: var(--login-text-secondary);
        font-size: 14px;
      }
    }

    .forgot-link {
      color: var(--login-link-color);
      font-size: 14px;

      &:hover {
        color: var(--login-link-hover);
      }
    }
  }
}

.register-section {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--login-border-color);

  .register-text {
    color: var(--login-text-secondary);
    font-size: 14px;
  }

  .register-link {
    color: var(--login-link-color);
    font-size: 14px;
    font-weight: 500;

    &:hover {
      color: var(--login-link-hover);
    }
  }
}

.login-icon {
  color: var(--login-primary-color);
  font-size: 16px;
}
</style>
